package com.imooc.api.intercept;

import com.imooc.base.BaseInfoProperties;
import com.imooc.exceptions.GraceException;
import com.imooc.grace.result.ResponseStatusEnum;
import com.imooc.utils.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 啊昌
 * @date 2025/9/11 21:32
 * SMSInterceptor 短信拦截器
 *  快速实现接口快捷键 ctrl + I
 */
@Component
@Slf4j
public class SMSInterceptor extends BaseInfoProperties implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String requestIp = IPUtil.getRequestIp(request); //获取到用户的ip
		boolean ipExist= redis.keyIsExist(MOBILE_SMSCODE + ":" + requestIp);
		if(ipExist){
			// 说明验证码还存在，在请求表示是频繁
			log.error("短信发送频率太高了~~！！！");
			GraceException.display(ResponseStatusEnum.SMS_NEED_WAIT_ERROR);
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
}
